package com.example.lxq.retrofit_rxjavatest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Observable;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private SeekBar sb_my;
    private TextView txt_total;
    private TextView txt_current;

    private Button btn_stop;
    private Button btn_cancel;
    private Button btn_start;


    private long currentLength = 0;
    private long totalLength;

    private final String musicStr = "http://59.110.159.15:8080/File/video/sichuanpendi.mp3";
    private final String videoStr = "http://59.110.159.15:8080/File/video/video1.mp4";
    private final String zipStr = "http://59.110.159.15:8080/File/video/sichuanpendiobj.zip";

    OkHttpClient client = null;

    private Call startCall = null;
    private Call stopCall = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        client = new OkHttpClient();
        initView();
    }


    private void initView() {
        sb_my = (SeekBar) findViewById(R.id.sb_my);
        txt_current = (TextView) findViewById(R.id.txt_current);
        txt_total = (TextView) findViewById(R.id.txt_total);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        btn_start = (Button) findViewById(R.id.btn_start);

        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (startCall != null && !startCall.isCanceled()) {
                    startCall.cancel();
                }

                if (stopCall != null && !stopCall.isCanceled()) {
                    stopCall.cancel();
                }
            }
        });

        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DownloadManager.getINSTANCE().download(musicStr, new DownloadObserver() {
                    @Override
                    public void onNext(DownloadInfo value) {
                        super.onNext(value);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });


                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getFileLength();
                    }
                }).start();


                downLoad();
            }
        });
    }

    private void getFileLength() {
        Request request = new Request.Builder().url(musicStr).build();
        try {
            Response response = client.newCall(request).execute();
            if (response != null && response.isSuccessful()) {
                long temLength = response.body().contentLength();
                response.close();
                totalLength = temLength == 0 ? -1 : temLength;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txt_total.setText(String.valueOf(totalLength));
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void downLoad() {

        if (currentLength == 0) {
            final Request request = new Request.Builder().url(musicStr).build();

            startCall = client.newCall(request);

            startCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response != null && response.isSuccessful()) {

                        String filepath = "/storage/emulated/0/EViewWorldData/test.jpg";

                        File file = new File(filepath);

                        InputStream is = null;
                        FileOutputStream outputStream = new FileOutputStream(file, true);

                        is = response.body().byteStream();

                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, len);
                            currentLength += len;

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (totalLength != 0)
                                        sb_my.setProgress((int) (currentLength * 100 / totalLength));
                                    txt_current.setText(String.valueOf(currentLength));
                                }
                            });
                        }
                        outputStream.flush();

                        is.close();
                        outputStream.close();
                    }
                }
            });
        } else if (currentLength > 0) {
            final Request request = new Request.Builder().addHeader("Range", "bytes=" + currentLength + "-" + totalLength).url(musicStr).build();

            stopCall = client.newCall(request);

            stopCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response != null && response.isSuccessful()) {
                        /*totalLength = response.body().contentLength();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txt_total.setText(String.valueOf(totalLength));
                            }
                        });*/


                        String filepath = "/storage/emulated/0/EViewWorldData/test.jpg";

                        File file = new File(filepath);
                        //RandomAccessFile file = new RandomAccessFile(filepath, "rw");


                        InputStream is = null;
                        FileOutputStream outputStream = new FileOutputStream(file, true);

                        is = response.body().byteStream();

                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, len);
                            currentLength += len;

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (totalLength != 0)
                                        sb_my.setProgress((int) (currentLength * 100 / totalLength));
                                    txt_current.setText(String.valueOf(currentLength));
                                }
                            });
                        }
                        outputStream.flush();

                        is.close();
                        outputStream.close();
                    }
                }

            });
        }
    }
}
